<?php
/**
 * View_Question
 *
 * Класс для отображения вопросов
 *
 * @author Гринько Виталий <perlaws@gmail.com>
 * @version 2.1
 */
class View_Question {

 public static $arrTimes = array(
      0=>'1 час',
      1=>'10 часов',
      2=>'24 часа',
      3=>'2 дня',
      4=>'5 дней',
      5=>'без ограничений'
    );
 public static $arrTimesBD = array(
      0 => 3600,   //1 час
      1 => 36000,  //10 часов
      2 => 86400,  //24 часа
      3 => 172800, //2 дня
      4 => 432000  //5 дней
    );
  public static function showQuestionAddEditForm($arrQuestion) {}


  /**
   * Вывод списка вопросов
   *
   */
  public static function showQuestionList(array $arrQuestions, $idFolder, $chapterDescription, $isLastChapter, $numberOfPages, $pageNum = 1, $arrUrls, $arrSort, $strFavLink) {
      View_TreeStructure::viewBreadcrumbs($arrUrls, false, $strFavLink); //выводим текущий путь
      self::showFilter($arrSort, $idFolder);
      if (empty($arrQuestions)) {
        self::_showNoContent($idFolder);
        return false;
      }
      echo '<div class="list_toggling">
              <table>
                <tr class="bg_grey">
                  <th></th>
                  <th>Вопрос</th>
                  <th style="width: 35px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_1.gif" height="14" width="16" title="Рейтинг" /></th>
                  <th style="width: 35px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_2.gif" title="Количество ответов" /></th>
                  <th style="width: 60px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_3.gif" title="Осталось до закрытия" /></th>'
                  //<th><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_4.gif" title="Опубликовано" /></th>
                .'</tr>';
//      if (sizeof($arrQuestions) == 0) {
//        if (!$isLastChapter)
//          echo '<div class="no-questions">В разделе пока нет вопросов</div>';
//      }
//      else {
        foreach ($arrQuestions as $arrQuestion) {
           echo '<tr idEssence="' . $arrQuestion['ID_question'] . '" essenceType="5">
           		<td class="fist_colum">
  							<a class="toggle_plus" href="#" onclick="View.ListToggling.toggleContent(this, ' . $arrQuestion['ID_question'] . ', 5); return false;" title="Развернуть вопрос" isDisabled="0"></a>';
           //Статус вопроса (до истечения действия)
           if (!is_NULL($arrQuestion['ID_best_answer'])) {
             $classNameStatus = 'time_ok';
             $classTitle = 'Ответ найден';
           }
           else {
             $expireStatus = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireStatus($arrQuestion['creation'], $arrQuestion['answer_time']) : 3;
             switch ($expireStatus) {
               case 0: $classNameStatus = 'time_red'; $classTitle = 'Время истекло';break;
               case 1: $classNameStatus = 'time_pred'; $classTitle = 'Время скоро истекает'; break;
               default: case 2: $classNameStatus = 'time'; $classTitle = 'Время ещё есть';break;
               case 3: $classNameStatus = 'time_inf'; $classTitle = 'Ограничения по времени отсутствуют'; break;
             }
           }
           echo '<span class="' . $classNameStatus . '" title="' . $classTitle . '"></span>';
    		echo '</td>';
           echo '<td>';
             echo View_UniversalInference::getQuestion($arrQuestion, false);
             //echo '<a href="' . W_ABSPATH . 'question/' . $arrQuestion['ID_question'] . '" title="Открыть вопрос" class="title">' . $arrQuestion['name'] . '</a>';
  					 //echo View_Tags::showTagsInList($arrQuestion['tags'], 5, '');
  				 echo '</td>';
           echo '<td><strong>' . round($arrQuestion['total_mark'], 2) . '</strong></td>';
           echo '<td><strong>' . ($arrQuestion['answer_amount'] + $arrQuestion['comment_amount']) . '</strong></td>';
           $expireTime = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireTimeLeft($arrQuestion['creation'], $arrQuestion['answer_time']) : '<span class="inf_symbol">&#8734</span>';
           echo '<td><span>' . (($expireTime === false || !is_NULL($arrQuestion['ID_best_answer'])) ? '—' : $expireTime). '</span></td>';
        }
      //}
      echo '  </table>';
    echo '</div>';
  }

public static function showQuestionListInSearch(array $arrQuestions) {
    echo '<div class="item">';
      echo '<div class="list_qwstion">
              <table>
                <tr class="bg_grey">
                  <th></th>
                  <th>Вопрос</th>
                  <th style="min-width: 50px;">Автор</th>
                  <th style="min-width: 20px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_1.gif" height="14" width="16" title="Рейтинг" /></th>
                  <th style="min-width: 20px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_2.gif" title="Количество ответов" /></th>
                  <th style="min-width: 10px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_3.gif" title="Осталось до закрытия" /></th>'
                  //<th><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_4.gif" title="Опубликовано" /></th>
                .'</tr>';
        foreach ($arrQuestions as $arrQuestion) {
           echo '<tr idQuestion="' . $arrQuestion['ID_question'] . '">
           		<td class="fist_colum">
  							';
           //Статус вопроса (до истечения действия)
           if (!is_NULL($arrQuestion['ID_best_answer'])) {
             $classNameStatus = 'time_ok';
             $classTitle = 'Ответ найден';
           }
           else {
             $expireStatus = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireStatus($arrQuestion['creation'], $arrQuestion['answer_time']) : 3;
             switch ($expireStatus) {
               case 0: $classNameStatus = 'time_red'; $classTitle = 'Время истекло';break;
               case 1: $classNameStatus = 'time_pred'; $classTitle = 'Время скоро истекает'; break;
               default: case 2: $classNameStatus = 'time'; $classTitle = 'Время ещё есть';break;
               case 3: $classNameStatus = 'time_inf'; $classTitle = 'Ограничения по времени отсутствуют'; break;
             }
           }
           echo '<span class="' . $classNameStatus . '" title="' . $classTitle . '"></span>';
    		echo '</td>';
           echo '<td>';
             echo '<a href="' . W_ABSPATH . 'question/' . $arrQuestion['ID_question'] . '">' . $arrQuestion['name'] . '</a>';
  					 echo View_Tags::showTagsInList($arrQuestion['tags'], 5, 'tags_qwestion');
  				 echo '</td>';
           echo '<td><a class="color_green" href="' . W_ABSPATH . 'user/' . $arrQuestion['login'] . '">' . $arrQuestion['login'] . '</a></td>';
           echo '<td><strong>' . round($arrQuestion['total_mark'], 2) . '</strong></td>';
           echo '<td><strong>' . $arrQuestion['answer_amount'] . '</strong></td>';
           $expireTime = $arrQuestion['answer_time'] != 5 ? str_replace(' ','&nbsp;', Service_Date::getQuestionExpireTimeLeft($arrQuestion['creation'], $arrQuestion['answer_time'])) : '<span class="inf_symbol">&#8734</span>';
           echo '<td><span>' . (($expireTime === false) ? '—' : $expireTime). '</span></td>';
  				 //echo '<td><span>' . Service_Date::getShortDateForUser($arrQuestion['creation']) . '</span></td>';
        }
      echo '  </table>
            </div>';
    echo '</div>';
  }

  /**
   * Вывод вопроса
   *
   * @param array $arrQuestion
   */
  public static function showQuestion(array $arrQuestion, $arrUrls, $profileFlag = false) {
   $objSession = User_Session::instance();
   echo '<div class="main_article">
           <div class="item_text_info">
             <div class="text_info_left">
               <div class="text_info_right">
                 <div class="item">';
             View_TreeStructure::viewBreadcrumbs($arrUrls); //выводим текущий путь
             echo '<div class="top_info_text">
                     <div class="right_ifno_text for_page_one_qwestion">
                     <ul class="rating">
      								 <li class="one">' . round($arrQuestion['total_mark'], 2) . '</li>
      							 </ul>
                       <ul class="info_coments margin_left">
                         <li class="date">' . Service_Date::getCaseDateForUser($arrQuestion['creation']) . '</li>
                         <li class="user"><a href="' . W_ABSPATH . 'user/' . $arrQuestion['login'] . '">' . $arrQuestion['login'] . '</a></li>
                       </ul>
                     </div>';
             if (!is_NULL($arrQuestion['ID_best_answer'])) {
               $classNameStatus = 'time_ok';
               $classTitle = 'Ответ найден';
               echo '<span class="ostalos_' . $classNameStatus . '" title="' . $classTitle . '">' . $classTitle . '</span>';
             } else {
               $expireTime = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireTimeLeft($arrQuestion['creation'], $arrQuestion['answer_time']) : '<span class="inf_symbol">&#8734</span>';
               $expireStatus = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireStatus($arrQuestion['creation'], $arrQuestion['answer_time']) : 3;
               switch ($expireStatus) {
                 case 0: $classNameStatus = 'time_red'; $classTitle = 'Время истекло';break;
                 case 1: $classNameStatus = 'time_pred'; $classTitle = 'Время скоро истекает'; break;
                 default: case 2: $classNameStatus = 'time'; $classTitle = 'Время ещё есть';break;
                 case 3: $classNameStatus = 'time_inf'; $classTitle = 'Ограничения по времени отсутствуют'; break;
               }
               echo '<span class="ostalos_' . $classNameStatus . '" title="' . $classTitle . '">' . (($expireTime === false) ? 'Время истекло' : ($arrQuestion['answer_time'] != 5 ? 'осталось: ' . $expireTime : 'без ограничений')) . '</span>';
             }
                   echo '</div>';
             echo '<div class="wysiwyg-content">';
               echo $arrQuestion['text'];
             echo '</div>';
             if (!$profileFlag){
	             echo '<ul class="bottom_ocenku bottom_ocenku_qone_qwestion">
	  								   <li><strong>Оцените вопрос:</strong><div class="kachestvo">';
	                      //выводим эл-т управления Оценка
	                      View_Mark::showMark(5, $arrQuestion, 0, 'stars');
	                   echo '</div></li>
	  								 </ul>';
	             echo View_Tags::showTags(split(',', $arrQuestion['tags']), $arrQuestion['ID_question'], 5, '', W_ABSPATH, ', ', $arrQuestion['userDeletedTagsInfo']);
             }
         echo '</div>
             </div>
           </div>
         </div>
       </div>';
   //if(is_NULL($arrQuestion['ID_best_answer']) && $objSession->isLoggedIn())
     //echo '<a href="' . W_ABSPATH . 'question/' . $arrQuestion['ID_question'] . '/answerAdd/0">Ответить</a>';
  }

  /**
   * Вывод блока с фильтром
   *
   */
  private static function showFilter($arrSort, $idFolder) {
    $objSession = User_Session::instance();
    echo '<div class="all_article list_qwestion">';
    $html = '
            <div class="filter-simple list_qwestion" style="display: ' . ($arrSort['questionFilter'] ? 'block' : 'none') . ';">
     				  <form action="' . W_ABSPATH . 'questions" method="GET" id="smallFilter">
     				    <table class="filterTable" border="0" cellspacing="0" cellpadding="0">
     				      <!--<tr>
     				        <th colspan="4">Фильтр</th>
     				      </tr>-->
     				      <tr>
     				        <td class="col_1">Теги</td>
     				        <td class="col_2" colspan="3">
     				          <input class="stFilterInput" type="text" id="tags" name="tags" value="' . (isset($arrSort['tags']) ? $arrSort['tags'] : '') . '" />
     				          <input id="tagsBtn" type="image" style="margin-top:2px;" name="sbmtShortFilter" src="' . W_IMAGES . 'button/btn_filter.gif" style="margin:0" />
     				          <input type="hidden" name="fullFilter" />
     				        </td>
     				      </tr>
     				     <tr>
     				       <td class="sbmt_left" colspan="4">
     				         <a id="showSorting" onClick="question.listView.filter.toggleFilter(this);return false;" href="#" style="margin-left:40px">Расширенная фильтрация и сортировка</a>
     				       </td>
     				     </tr>
     				    </table>
     				  </form>
      		  </div>
    		  ';
    $html .= '  <div class="filter list_qwestion" style="display: ' . (!$arrSort['questionFilter'] ? 'block' : 'none') . ';">
     				  <form action="' . W_ABSPATH . 'questions" method="GET" id="fullFilter">
     				    <table class="filterTable" border="0" cellspacing="0" cellpadding="0">
     				     <tr>
     				       <th colspan="4">Фильтр</th>
     				     </tr>
     				     <tr>
     				       <td class="col_1">Создано после</td>
     				       <td class="col_2"><input class="datePicker" type="text" name="startDate" id="startDate" value="' . (!empty($arrSort['startDate']) ? $arrSort['startDate'] : '') . '" /></td>
     				       <td class="col_3">Рейтингом более</td>
     				       <td class="col_4"><input class="datePicker" type="text" size="1" id="rating" name="rating" value="' . (!empty($arrSort['rating']) ? $arrSort['rating'] : '') . '" /></td>
     				     </tr>
     				     <tr>
     				       <td class="col_1">до</td>
     				       <td class="col_2">
     				         <input class="datePicker" type="text" name="endDate" id="endDate" value="' . (!empty($arrSort['startDate']) ? $arrSort['endDate'] : NULL) . '"/>
     				         <p class="duration" style="display: block;"><a class="jsHref" onclick="question.listView.filter.setDay();">День</a>&nbsp;&nbsp;<a class="jsHref" onclick="question.listView.filter.setWeek();">Неделя</a>&nbsp;&nbsp;<a class="jsHref" onclick="question.listView.filter.setMonth();">Месяц</a>&nbsp;&nbsp;<a class="jsHref" onclick="question.listView.filter.setYear();">Год</a></p>
     				       </td>
     				       <td class="col_3" colspan="2" style="text-align:left"><input type="checkbox" name="actual" value="' . (!empty($arrSort['actual']) && $arrSort['actual'] ? '1' : '') . '" ' . (!empty($arrSort['actual']) && $arrSort['actual'] ? 'checked="checked"' : '') . ' />&nbsp;&nbsp;Только актуальные</td>
     				       <!--<td class="col_4"></td>-->
     				     </tr>
     				     <tr>
     				       <td class="col_1" style="padding-top: 7px;">Укажите теги</th>
     				       <td class="col_2" colspan="3"><input class="stFilterInput" type="text" id="tags" name="tags" value="' . (isset($arrSort['tags']) ? $arrSort['tags'] : '') . '" /></th>
     				     </tr>
     				     <tr>
     				       <th colspan="4" style="padding-top: 15px;">Сортировка</th>
     				     </tr>
     				     <tr>
     				       <td class="col_1" style="padding-top: 7px;">Выберите поле</th>
     				       <td class="col_2">
                     <select id="sort" name="sort">
							  		 	 <option value="1" ' . ($arrSort['sort'] == 1 ? 'selected="selected"' : NULL) . '>Дата</option>
							  		 	 <option value="2" ' . ($arrSort['sort'] == 2 ? 'selected="selected"' : NULL) . '>Рейтинг</option>
							  		 	 <!--<option value="3" ' . ($arrSort['sort'] == 3 ? 'selected="selected"' : NULL) . '>Сложность</option>-->
							  			 <option value="4" ' . ($arrSort['sort'] == 4 ? 'selected="selected"' : NULL) . '>Количесво ответов</option>
							  			 <option value="5" ' . ($arrSort['sort'] == 5 ? 'selected="selected"' : NULL) . '>Количество просмотров</option>
							  			 <option value="6" ' . ($arrSort['sort'] == 6 ? 'selected="selected"' : NULL) . '>Количество посетителей</option>
							  		 </select>
     				       </td>
     				       <td class="col_3" colspan="2" style="padding-right:7px;padding-left:10px;">
       				       <label for="direction_1" style="padding-top:0px; padding-right:0px;">&nbsp;прямой порядок</label>
       				       <input type="radio" name="direction" id="direction_1" style="position:relative;left:1px" value="1" ' . ($arrSort['direction'] != 2 ? 'checked' : NULL) . '><br />
       				       <label for="direction_2" style="padding-top:0px; padding-right:0px;">&nbsp;обратный порядок</label>
  						  		 <input type="radio" name="direction" id="direction_2" value="2" ' . ($arrSort['direction'] == 2 ? 'checked' : NULL) . '>
     				       </td>
     				     </tr>
     				     <tr>
     				       <td colspan="4" style="font-size:1px;height:5px;"></th>
     				     </tr>
     				     <tr>
     				       <td class="sbmt_left" colspan="2">
     				         <input id="tagsBtn" type="image" name="sbmtBigFilter" src="' . W_IMAGES . 'button/btn_filter.gif" style="margin:0" />
     				         <input type="hidden" name="fullFilter" />
     				       </td>
     				       <td class="sbmt_right" colspan="2">
     				         <a id="showSorting" onClick="question.listView.filter.toggleFilter(this);return false;" href="#">Обычный фильтр</a>
     				       </td>
     				     </tr>
     				    </table>
     				  </form>
      			</div>';
		View_Common::showRoundedBox($html, 'width: 460px;margin-top:12px;height:auto;');
	  echo '    			</div>';

  }

  /**
   * отображение простого списка вопросов, как на главной
   */
  public static function showQuestionListSimple($arrQuestion){
		foreach ($arrQuestion as $arr){
			echo '
			<ul>
				' . ($arr['show_folder'] == 0 ? '<li><a href="' . W_ABSPATH . 'questions?folder=' . $arr['ID_root_folder'] . '&pageNum=1">' . $arr['root_folder_name'] . '</a></li>' : NULL) . '
				<li><a href="' . W_ABSPATH . 'questions?folder=' . $arr['ID_folder'] . '&pageNum=1">' . $arr['folderName'] . ' </a></li>
				<li class="last"><a href="' . W_ABSPATH . 'question/' . $arr['ID_question'] . '">' . $arr['name'] . '</a></li>
			</ul>';
		}
  }

  private static function _showChapterOption(array $arrChapter, $ID_question_chapter = NULL, $spaces) {
  	if ($arrChapter['ID_question_chapter'] == $ID_question_chapter)
  	  $selected = 'selected';
  	else
  	  $selected = '';
    echo '<option value="' . $arrChapter['ID_question_chapter'] . '" ' . $selected . '> ' . $spaces . ' ' . $arrChapter['name'] . '</option>';
  }

  /**
   * Отображение элемента формы для выбора количества дней на ответ (при добавлении вопроса)
   *
 * @param int $selected - выбранное значение
   */
  public static function showDaysToAnswerSelectBox($selected = 2) {
    
    echo '<select name="question[answer_time]">';
    $sizeArr = sizeof(self::$arrTimes);
    for ($i = 0; $i < $sizeArr; $i++) {
      $strSelected = ($i == $selected) ? ' selected="selected"' : '';
      echo '<option  value="' . $i . '"' . $strSelected . '>' . self::$arrTimes[$i] . '</option>';
    }
    echo '</select>';
  }

  private static function _showNoContent($idFolder = NULL) {
    if (is_null($idFolder)) $idFolder = 0;
    echo '<div class="no_essences_notice">
					  <p>Вопросов по данному запросу не найдено.</p>
  	        <p>Вы можете <a href="' . W_ABSPATH . 'question/add/' . $idFolder . '">добавить вопрос</a><a href="' . W_ABSPATH . 'question/add/' . $idFolder . '"><img class="arrowRight" src="' . W_IMAGES . 'arrowRight.gif" alt="" /></a></p>
  	      </div>';
  }

  public function __destruct() {}

}
?>